package com.hm.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.hm.common.util.FileUtil;
import com.hm.common.util.ResourceUtil;
import com.hm.oper_monitor.constants.Constants;

public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

	public void setCallerPropFiles(Set<String> callerPropFiles) {
		Properties properties = new Properties();
		for (String callerPropFile : callerPropFiles) {
			if (callerPropFile.equals(Constants.configPropFileName)){
//				获取操作系统用户路径
//				String user_home = System.getProperty("user.home");
				String caller_home = null;
				try {
					caller_home = ResourceUtil.getApplicationPath(this.getClass());
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				File file = new File(caller_home + File.separatorChar + Constants.configPropFileName);
				try {
					logger.info("Loading properites file from " + file);
					if (!file.exists()){
						InputStream is= this.getClass().getClassLoader().getResourceAsStream("config/" + Constants.configPropFileName);
						FileUtil.copyFile(file, is);
						if (is != null){
							is.close();
						}
					}
					Properties prop = new Properties();
					prop.load(new FileInputStream(file));
					logger.debug("Properties -> " + prop);
					if (prop != null) {
						properties.putAll(prop);
					}
				} catch (Exception e) {
					logger.debug(new Exception("Properties file " + callerPropFile + " cannot be found. All related functionalities may be unavailable"));
				}
			}
		}
		// 关键方法,调用的PropertyPlaceholderConfigurer中的方法,通过这个方法将自定义加载的properties文件加入spring中
		this.setProperties(properties);
	}

}
